//
//  MJRefreshHeader.swift
//  OC-Swift
//
//  Created by 陆文宇 on 2017/2/14.
//  Copyright © 2017年 陆文宇. All rights reserved.
//

import UIKit

class MJRefreshHeader: MJRefreshComponent {
    
    var _lastUpdatedTimeKey: String?
    var lastUpdatedTimeKey: String {
        set {
            _lastUpdatedTimeKey = newValue
        }
        
        get {
            return _lastUpdatedTimeKey!
        }
    }
    var lastUpdatedTime: Date? {
        return UserDefaults.standard.object(forKey: lastUpdatedTimeKey) as? Date
    }
    var ignoredScrollViewContentInsetTop: CGFloat = 0
    private var insetTDelta: CGFloat?
    override var state: MJRefreshComponent.MJRefreshState {
        set {
            let oldState: MJRefreshState = super.state
            if super.state != newValue {
                super.state = newValue
            }
            
            if state == .idle {
                if oldState != .refreshing {
                    return
                }
                
                UserDefaults.standard.set(Date(), forKey: lastUpdatedTimeKey)
                UserDefaults.standard.synchronize()
                
                UIView.animate(withDuration: MJRefreshSlowAnimationDuration, animations: { 
                    self.scrollView?.mj_insetT += self.insetTDelta!
                    
                    if self.automaticallyChangeAlpha {
                        self.alpha = 0
                    }
                }, completion: { (finished) in
                    self.pullingPercent = 0
                    
                    if self.endRefreshingCompletionClosure != nil {
                        self.endRefreshingCompletionClosure!()
                    }
                })
            } else if state == .refreshing {
                DispatchQueue.main.async {
                    UIView.animate(withDuration: MJRefreshFastAnimationDuration, animations: { 
                        let top: CGFloat = self.scrollViewOriginalInset!.top + self.mj_h
                        self.scrollView?.mj_insetT = top
                        self.scrollView?.setContentOffset(CGPoint(x: 0, y: -top), animated: false)
                    }, completion: { (finished) in
                        self.executeRefreshingCallback()
                    })
                }
            }
        }
        
        get {
            return _state
        }
    }
    init(refreshingClosure: @escaping MJRefreshComponentRefreshingClosure) {
        super.init(frame: .zero)
        
        self.refreshingClosure = refreshingClosure
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    override func prepare() {
        super.prepare()
        
        lastUpdatedTimeKey = MJRefreshHeaderLastUpdatedTimeKey
        mj_h = MJRefreshHeaderHeight
    }
    
    override func placeSubviews() {
        super.placeSubviews()
        
        mj_y = -mj_h - ignoredScrollViewContentInsetTop
    }
    
    override func scrollViewContentOffsetDidChange(change: Dictionary<NSKeyValueChangeKey, Any>) {
        super.scrollViewContentOffsetDidChange(change: change)
        
        if state == .refreshing {
            guard window != nil else {
                return
            }
            
            var insetT: CGFloat = -scrollView!.mj_offsetY > scrollViewOriginalInset!.top ? -scrollView!.mj_offsetY : scrollViewOriginalInset!.top
            insetT = insetT > mj_h + scrollViewOriginalInset!.top ? mj_h + scrollViewOriginalInset!.top : insetT
            scrollView?.mj_insetT = insetT
            
            insetTDelta = scrollViewOriginalInset!.top - insetT
            return
        }
        
        scrollViewOriginalInset = scrollView!.contentInset
        
        let offsetY: CGFloat = scrollView!.mj_offsetY
        let happenOffsetY: CGFloat = -scrollViewOriginalInset!.top
        
        if offsetY > happenOffsetY {
            return
        }
        
        let normal2pullingOffsetY: CGFloat = happenOffsetY - mj_h
        let pullingPercent: CGFloat = (happenOffsetY - offsetY) / mj_h
        
        if scrollView!.isDragging {
            self.pullingPercent = pullingPercent
            if state == .idle && offsetY < normal2pullingOffsetY {
                state = .pulling
            } else if state == .pulling && offsetY >= normal2pullingOffsetY {
                state = .idle
            }
        } else if state == .pulling {
            beginRefreshing()
        } else if pullingPercent < 1 {
            self.pullingPercent = pullingPercent
        }
    }
    
    override func endRefreshing() {
        DispatchQueue.main.async {
            self.state = .idle
        }
    }

    /*
    // Only override draw() if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func draw(_ rect: CGRect) {
        // Drawing code
    }
    */

}
